<!-- eslint-disable vue/multi-word-component-names -->
<script setup>
import { watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useFreeze } from '@/stores/Freeze';
import { computed } from 'vue';

const store = useFreeze();
const isPurchaseButtonDisabled = computed(() => store.isPurchaseButtonDisabled);



// 接收来自父组件的 props
const props = defineProps({
  goodslist: {
    type: Object,
    required: true,
  },

});


// 监听 goodslist 的变化
watch(() => props.goodslist, (newVal) => {
  console.log("Received goodslist in <show />:", newVal);
});
// 在 show.vue 中
watch(() => store.isPurchaseButtonDisabled, (newVal) => {
  console.log('Button disabled status in show:', newVal);
});


import { ref } from 'vue';

const purchaseDialogVisible = ref(false);
const buyerInfo = ref({
  goods: '',
  buyerName: '',
  buyerPhone: '',
  tradeTime: '',
  tradeAddress: '',
});

const rules = {
  buyerName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  buyerPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' },],
  tradeTime: [
    { required: true, message: '请选择交易时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请选择交易时间'));
        }
        const currentTime = new Date().getTime();
        const selectedTime = new Date(value).getTime();
        if (selectedTime < currentTime) {
          return callback(new Error('交易时间不能早于当前时间'));
        }
        callback();
      },
      trigger: 'change',
    },
  ],
  tradeAddress: [
    { required: true, message: '请选择交易地点', trigger: 'change' },
  ],
};

function onPurchase() {
  buyerInfo.value.goods = props.goodslist; // 在点击购买时动态设置商品ID
  purchaseDialogVisible.value = true;
}
const purchaseForm = ref(null);
const submitPurchase = async () => {
  try {
    const valid = await new Promise((resolve) => {
      purchaseForm.value.validate(resolve);
    });
    
    if (valid) {
     
      const response = await fetch('http://localhost:8080/buyers', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
       
        body: JSON.stringify(buyerInfo.value),
      });

      if (!response.ok) {
        throw new Error('网络响应不是 OK');
      }

      ElMessage({ type: 'success', message: '提交成功' });
      purchaseDialogVisible.value = false;
      resetForm();
    } else {
      ElMessage({ type: 'error', message: '请完善购买信息！' });
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage({ type: 'error', message: '提交失败，请重试！' });
  }
}

function resetForm() {
  buyerInfo.value = {
    goods: '',
    buyerName: '',
    buyerPhone: '',
    tradeTime: '',
    tradeAddress: '',
  };
}

</script>











<template>
  <div class="show">
  <div class="purchase-product">
    <!-- 商品信息展示 -->
    <div class="product-info">
      <el-image
        :src="goodslist.image"
        fit="cover"
        class="product-image"
      ></el-image>
      <div class="product-details">
        <h2>{{ goodslist.name }}</h2>
        <p>价&nbsp;&nbsp;格: <strong class="price">¥{{ goodslist.price }}</strong></p>
        <p>库&nbsp;&nbsp;存: <strong class="price">{{ goodslist.stock }}</strong></p><!--库存样式没写，先用price的-->
        <p v-if="goodslist.description">描&nbsp;&nbsp;述: <strong>{{ goodslist.description }}</strong></p>
      </div>
    </div>

    <!-- 购买按钮 -->
   
    <el-button v-if="isPurchaseButtonDisabled" type="primary" @click="onPurchase" class="purchase-btn">
      购买
     </el-button>
    <!-- 购买信息输入对话框 -->
    <el-dialog
      title="填写购买信息"
      v-model="purchaseDialogVisible"
      width="30%"
      class="purchase-dialog"
    >
      <el-form ref="purchaseForm" :model="buyerInfo" :rules="rules">
        <!-- 商品ID，隐藏字段 -->
        <input type="hidden" v-model="buyerInfo.goods"/>
       
        <el-form-item label="姓名" prop="buyerName">
          <el-input v-model="buyerInfo.buyerName" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="buyerPhone">
          <el-input v-model="buyerInfo.buyerPhone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="交易时间" prop="tradeTime">
          <el-date-picker
            v-model="buyerInfo.tradeTime"
            type="datetime"
            placeholder="请选择交易时间"
          ></el-date-picker>
        </el-form-item>

        <!-- 选择交易地点 -->
        <el-form-item label="交易地点" prop="tradeAddress">
          <el-select v-model="buyerInfo.tradeAddress" placeholder="请选择交易地点">
            <el-option label="杭州市上城区" value="上城区"></el-option>
            <el-option label="杭州市拱墅区" value="拱墅区"></el-option>
            <el-option label="杭州市西湖区" value="西湖区"></el-option>
            <el-option label="杭州市滨江区" value="滨江区"></el-option>
            <el-option label="杭州市萧山区" value="萧山区"></el-option>
            <el-option label="杭州市余杭区" value="余杭区"></el-option>
            <el-option label="杭州市富阳区" value="富阳区"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="purchaseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPurchase">提交</el-button>
      </template>
    </el-dialog>
  </div>
</div>
</template>







<style scoped>
.show{
  display: flex;
  height: 100vh;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
 
}
.purchase-product {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-width: 450px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}

.product-page{
  max-width: 90%;
  margin: 0 auto;
}

.product-images{
  text-align: center;
}

.product-info {
  text-align: center;
}

.product-image {
  width: 100%;
  height: 250px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.product-details {
  margin-top: 15px;
}

.price {
  color: #e53935;
  font-size: 1.5em;
}

.purchase-btn {
  font-size: 1.2em;
  width: 100%;
  padding: 12px 0;
  border-radius: 8px;
  background-color: #50c9c3;
  border: none;
}

.purchase-btn:hover {
  background-color: #4e73df;
}

.purchase-dialog {
  border-radius: 12px;
}

.nav {
  display: flex;
  gap: 20px;
  padding: 20px;
  justify-content: center;
}

.scroll-top-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  cursor: pointer;
}

.section {
  padding: 20px;
  border: 1px solid #ccc;
  background-color: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  margin-bottom: 20px;
}

.product-display-image {
  max-width: 100%;
  height: auto;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.product-information {
  display: flex;
  flex-direction: column; /* 让标题和表格竖直排列 */
  align-items: center; /* 水平居中 */
  margin-bottom: 30px; /* 控制表格与底部的距离 */
}

.product-details-table {
  width: 100%;
  max-width: 600px;
  border-collapse: collapse;
  margin-top: 20px;
}

.product-details-table th,
.product-details-table td {
  border: 1px solid #ccc;
  padding: 15px;
  text-align: left;
  background-color: #f9f9f9;
}

.product-details-table th {
  background-color: #e0e0e0;
}

</style>
